package encome.work.service.impl;

import cn.hutool.extra.emoji.EmojiUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import encome.work.dao.Message;
import encome.work.mapper.MessageMapper;
import encome.work.service.MessageSevice;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements MessageSevice {
    @Resource
    MessageMapper messageMapper;
    public void add(Message message){
        if(EmojiUtil.containsEmoji(message.getContent())){
            message.setContent(EmojiUtil.toAlias(message.getContent()));
        }
        messageMapper.insert(message);
    }
    public List<Message> selectMessageToUser(long toId){
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Message::getTo,toId);
        return explainEmoji(messageMapper.selectList(queryWrapper));
    }

    @Override
    public List<Message> selectMessageFromUser(long fromId) {
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Message::getFrom,fromId);
        return explainEmoji(messageMapper.selectList(queryWrapper));
    }

    @Override
    public List<Message> selectMessageConnectUser(long user_id) {
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Message::getTo,user_id)
                .or()
                .eq(Message::getFrom,user_id);
        return explainEmoji(messageMapper.selectList(queryWrapper));
    }

    @Override
    public List<Message> selectMessageConnectUserFromTimeToTime(long user_id, Date start, Date end) {
        LambdaQueryWrapper<Message> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .ge(Message::getTime,start)
                .le(Message::getTime,end)
                .and(qw->qw.eq(Message::getTo,user_id)
                        .or()
                        .eq(Message::getFrom,user_id));
        return explainEmoji(messageMapper.selectList(queryWrapper));
    }
    public List<Message> explainEmoji(List<Message> messages){
        messages.forEach(message -> {
            if(EmojiUtil.containsEmoji(message.getContent())){
                message.setContent(EmojiUtil.toUnicode(message.getContent()));
            }
        });
        return messages;
    }
}
